import React, { useLayoutEffect, useState } from 'react';

import { Alert, Message } from 'antd';
import { ActivityIndicator, Modal, WhiteSpace } from 'antd-mobile';
import moment from 'moment';
import { router, withRouter } from 'umi';

import { createDictionary } from '@/dictionary';
import { defaultFormatResult, useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import EntryMetaTag from '@/pages/EntryManage/mobile/components/EntryMetaTag';
import { fetchEmployeeArchivesData, getFirstSimpleInfo, postStatement } from '@/pages/EntryManage/services';
import { Header, ListItem } from '@/pages/RecruitEmail/mobile/components';
import imageAdd from '@/pages/Recruitment/External/images/icon-add.png';

import EmployeeCard from './components/EmployeeCard';
import styles from './index.less';

const [, getWorkExperienceText] = createDictionary('WORK_EXPERIENCE_DICT', { textKey: 'label' });
const formatDate = (startTime, endTime) => {
    const st = (startTime && moment(startTime).format('YYYY.MM')) || '';
    const et = (endTime && moment(endTime).format('YYYY.MM')) || (startTime && '至今');
    return st && et ? `${st}-${et}` : '';
};

const ListItemHead = ({ title, extra }) => (
    <div className="itemHead">
        <div className="itemHeadTitle">{title}</div>
        <div className="itemHeadExtra">{extra}</div>
    </div>
);

const STATEMENT_STR = `修改个人档案即代表您已认真阅读并同意接受以下声明：<br/>
    1、个人档案中所提供的信息是全面且准确的；<br/>
    2、公司可对个人档案中有关的信息进行调查，公司亦有权查阅本人各种材料以及向第三方做个人访谈（如应聘者原雇主、家庭成员、业务联系人、经济来源人、朋友等）。<br/>
    3、由于本人提供虚假信息的，公司方面有权在核实后随时终止劳动合同。<br/>`;

const AddButton = ({ ...rest }) => (
    <ListItem
        title={
            <div className="listItemControl">
                <img alt="" src={imageAdd} />
                添加
            </div>
        }
        showArrow={false}
        {...rest}
    />
);

/**
 * 入职员工详情
 */
const EntryEmployeeDetailMobile = ({ location }) => {
    const [pageError, setPageError] = useState();
    const { entryPersonnelCode } = location.query;
    // 申明弹框
    const [modalVisible, setModalVisible] = useState(false);
    // 获取入职人员信息, 判断申明的数据
    useRequest(() => getFirstSimpleInfo({ entryPersonnelCode }), {
        onSuccess: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    const { archiveUpdateTime } = data;
                    if (archiveUpdateTime.length > 0) {
                        setModalVisible(false);
                    } else {
                        setModalVisible(true);
                    }
                } else {
                    Message.error(msg);
                }
            }
        }
    });
    // 获取数据
    const {
        data: employeeArchivesData,
        error: fetchEmployeeArchivesInfoError,
        loading: fetchEmployeeArchivesInfoLoading
    } = useRequest(() => fetchEmployeeArchivesData(entryPersonnelCode), {
        cacheKey: `entry-employee-baseInfo-${entryPersonnelCode}`,
        cacheTime: 3600000,
        // refreshOnWindowFocus: true,
        refreshDeps: [entryPersonnelCode],
        ready: !!entryPersonnelCode,
        ...defaultFormatResult
    });
    const [, getEmergencyRelationshipText] = useDictionary('emergencyRelationship', { textKey: 'label' });
    const [, getIndustryTypeText] = useDictionary('industryType', { textKey: 'label' });
    const [, getDegreeTypeText] = useDictionary('agreeType', { textKey: 'label' });
    const [, getLangHearSpeakLevelText] = useDictionary('lang_hear_speak_level', { textKey: 'label' });
    const [, getLangReadWriteLevelText] = useDictionary('lang_read_write_level', { textKey: 'label' });
    const [, getSkillLevelText] = useDictionary('skill_level', { textKey: 'label' });
    const [, getLangTypeText] = useDictionary('recruitTalentLangType', { textKey: 'label' });
    const { awardList, eduList, familyList, langList, skillList, trainList, workList } = employeeArchivesData || {};

    // 提交声明
    const { run: submitStatement } = useRequest(
        () => postStatement({ entryPersonnelCode, archiveTip: STATEMENT_STR }),
        {
            manual: true,
            onSuccess: res => {
                const { code, msg } = res;
                if (code === 10000) {
                    setModalVisible(false);
                } else {
                    Message.error(msg);
                }
            }
        }
    );

    // 我知道了
    const handleOk = () => {
        submitStatement();
    };
    // 取消
    // const handleCancel = () => {
    //     setModalVisible(false);
    // };

    const handleRoute = (path, flag) => {
        if (flag) {
            return;
        }
        history.push(path);
    };

    useLayoutEffect(() => {
        // 参数校验
        if (!entryPersonnelCode) {
            setPageError('参数无效');
        }
    }, [entryPersonnelCode]);

    if (pageError || fetchEmployeeArchivesInfoError) {
        return (
            <>
                <Alert
                    message={pageError?.msg || fetchEmployeeArchivesInfoError?.msg || '加载错误'}
                    type="error"
                    showIcon
                />
            </>
        );
    }

    return (
        <>
            {fetchEmployeeArchivesInfoLoading && <ActivityIndicator toast text="正在加载" />}
            {employeeArchivesData ? (
                <div className={styles.entryMobileContainer}>
                    <EntryMetaTag />
                    <Header />
                    <EmployeeCard
                        employeeArchivesData={employeeArchivesData}
                        onClick={() =>
                            history.push({
                                pathname: '/blank/entryManage/entryEmployeeDetail/basic',
                                query: { entryPersonnelCode }
                            })
                        }
                    />
                    <WhiteSpace size="md" />
                    <div className="formContainer">
                        {/* 表单主题 */}
                        {/* 紧急联系人 */}
                        <ListItem
                            title="紧急联系人"
                            showArrow={!employeeArchivesData.emergencyContact}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/emergencyContact',
                                        query: { entryPersonnelCode }
                                    },
                                    !!employeeArchivesData.emergencyContact
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: familyList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {employeeArchivesData.emergencyContact && (
                                <ListItem
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={<ListItemHead title={employeeArchivesData.emergencyContact} />}
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/emergencyContact',
                                            query: { entryPersonnelCode }
                                        })
                                    }
                                >
                                    <div className="formItemValue">
                                        {getEmergencyRelationshipText(employeeArchivesData.emergencyRelationship)}
                                    </div>
                                </ListItem>
                            )}
                        </ListItem>
                        <WhiteSpace size="md" />
                        {/* 家庭成员 */}
                        <ListItem
                            title="家庭成员"
                            showArrow={!(familyList?.length > 0)}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/family',
                                        query: { entryPersonnelCode }
                                    },
                                    familyList?.length > 0
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: familyList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {familyList?.map(item => (
                                <ListItem
                                    key={item.id}
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={<ListItemHead title={item.name} />}
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/family',
                                            query: { entryPersonnelCode, id: item.id }
                                        })
                                    }
                                >
                                    <div className="formItemValue">{getEmergencyRelationshipText(item.relation)}</div>
                                </ListItem>
                            ))}
                        </ListItem>
                        {familyList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/blank/entryManage/entryEmployeeDetail/family',
                                        query: { entryPersonnelCode }
                                    })
                                }
                            />
                        )}
                        <WhiteSpace size="md" />
                        {/* 工作经验 */}
                        <ListItem
                            title="工作经验"
                            showArrow={!(workList?.length > 0)}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/workExperience',
                                        query: { entryPersonnelCode }
                                    },
                                    workList?.length > 0
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: workList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {employeeArchivesData.workExperience > 1 && (
                                <div className={styles.mb16}>
                                    {getWorkExperienceText(employeeArchivesData.workExperience)}
                                </div>
                            )}
                            {workList?.map(item => (
                                <ListItem
                                    key={item.id}
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={
                                        <ListItemHead
                                            title={item.organize}
                                            extra={formatDate(item.startTime, item.endTime)}
                                        />
                                    }
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/workExperience',
                                            query: { entryPersonnelCode, id: item.id }
                                        })
                                    }
                                >
                                    <div className="formItemValue">
                                        {getIndustryTypeText(item.industry)}-{item.post}
                                    </div>
                                    {item.reason && <div className="contentStyle">{item.reason}</div>}
                                </ListItem>
                            ))}
                        </ListItem>
                        {workList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/blank/entryManage/entryEmployeeDetail/workExperience',
                                        query: { entryPersonnelCode }
                                    })
                                }
                            />
                        )}
                        <WhiteSpace size="md" />
                        {/* 教育经历 */}
                        <ListItem
                            title="教育经历"
                            showArrow={!(eduList?.length > 0)}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/educationalExperience',
                                        query: { entryPersonnelCode }
                                    },
                                    eduList?.length > 0
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: eduList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {eduList?.map(item => (
                                <ListItem
                                    key={item.id}
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={
                                        <ListItemHead
                                            title={item.graduateSchool}
                                            extra={formatDate(item.startTime, item.endTime)}
                                        />
                                    }
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/educationalExperience',
                                            query: { entryPersonnelCode, id: item.id }
                                        })
                                    }
                                >
                                    <div className="formItemValue">
                                        {getDegreeTypeText(item.degree)}-{item.major}
                                    </div>
                                </ListItem>
                            ))}
                        </ListItem>
                        {eduList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/blank/entryManage/entryEmployeeDetail/educationalExperience',
                                        query: { entryPersonnelCode }
                                    })
                                }
                            />
                        )}
                        <WhiteSpace size="md" />
                        {/* 培训经历 */}
                        <ListItem
                            title="培训经历"
                            showArrow={!(trainList?.length > 0)}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/trainingExperience',
                                        query: { entryPersonnelCode }
                                    },
                                    trainList?.length > 0
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: trainList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {trainList?.map(item => (
                                <ListItem
                                    key={item.id}
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={
                                        <ListItemHead
                                            title={item.trainOrganize || '其他机构'}
                                            extra={formatDate(item.startTime, item.endTime)}
                                        />
                                    }
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/trainingExperience',
                                            query: { entryPersonnelCode, id: item.id }
                                        })
                                    }
                                >
                                    <div className="formItemValue">{item.trainContent}</div>
                                </ListItem>
                            ))}
                        </ListItem>
                        {trainList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/blank/entryManage/entryEmployeeDetail/trainingExperience',
                                        query: { entryPersonnelCode }
                                    })
                                }
                            />
                        )}
                        <WhiteSpace size="md" />
                        {/* 获奖记录 */}
                        <ListItem
                            title="获奖记录"
                            showArrow={!(awardList?.length > 0)}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/awardRecord',
                                        query: { entryPersonnelCode }
                                    },
                                    awardList?.length > 0
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: awardList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {awardList?.map(item => (
                                <ListItem
                                    key={item.id}
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={
                                        <ListItemHead
                                            title={item.awardName || '其他'}
                                            extra={item.awardTime && moment(item.awardTime).format('YYYY.MM.DD')}
                                        />
                                    }
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/awardRecord',
                                            query: { entryPersonnelCode, id: item.id }
                                        })
                                    }
                                >
                                    <div className="formItemValue">{item.organize}</div>
                                </ListItem>
                            ))}
                        </ListItem>
                        {awardList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/blank/entryManage/entryEmployeeDetail/awardRecord',
                                        query: { entryPersonnelCode }
                                    })
                                }
                            />
                        )}
                        <WhiteSpace size="md" />
                        {/* 语言能力 */}
                        <ListItem
                            title="语言能力"
                            showArrow={!(langList?.length > 0)}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/languages',
                                        query: { entryPersonnelCode }
                                    },
                                    langList?.length > 0
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: langList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {langList?.map(item => (
                                <ListItem
                                    key={item.id}
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={<ListItemHead title={getLangTypeText(item.langType)} />}
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/languages',
                                            query: { entryPersonnelCode, id: item.id }
                                        })
                                    }
                                >
                                    <div className="formItemValue">
                                        {item.listenSpeakAbility !== undefined && (
                                            <span>
                                                听说{getLangHearSpeakLevelText(item.listenSpeakAbility?.toString())}
                                            </span>
                                        )}
                                        {item.listenSpeakAbility !== undefined &&
                                            item.readWriteAbility !== undefined &&
                                            ' · '}
                                        {item.listenSpeakAbility !== undefined && (
                                            <span>
                                                读写{getLangReadWriteLevelText(item.readWriteAbility?.toString())}
                                            </span>
                                        )}
                                    </div>
                                </ListItem>
                            ))}
                        </ListItem>
                        {langList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/blank/entryManage/entryEmployeeDetail/languages',
                                        query: { entryPersonnelCode }
                                    })
                                }
                            />
                        )}
                        <WhiteSpace size="md" />
                        {/* 专业技能 */}
                        <ListItem
                            title="专业技能"
                            showArrow={!(skillList?.length > 0)}
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/blank/entryManage/entryEmployeeDetail/skills',
                                        query: { entryPersonnelCode }
                                    },
                                    skillList?.length > 0
                                )
                            }
                            titleStyle={{ fontWeight: 'bold', paddingBottom: skillList?.length > 0 ? 8 : 16 }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {skillList?.map(item => (
                                <ListItem
                                    key={item.id}
                                    bordered={false}
                                    style={{ paddingLeft: 0, paddingRight: 0 }}
                                    title={<ListItemHead title={item.skillName} />}
                                    titleStyle={{ paddingTop: 4, paddingBottom: 4 }}
                                    onClick={() =>
                                        handleRoute({
                                            pathname: '/blank/entryManage/entryEmployeeDetail/skills',
                                            query: { entryPersonnelCode, id: item.id }
                                        })
                                    }
                                >
                                    <div className="formItemValue">
                                        {item.skillDuration ? `${item.skillDuration} 月 · ` : ''}
                                        {getSkillLevelText(item?.proficiency?.toString())}
                                    </div>
                                </ListItem>
                            ))}
                        </ListItem>
                        {skillList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/blank/entryManage/entryEmployeeDetail/skills',
                                        query: { entryPersonnelCode }
                                    })
                                }
                            />
                        )}
                        <WhiteSpace size="md" />
                    </div>
                    <Modal
                        visible={modalVisible}
                        transparent
                        className={styles.modalMaterialsTips}
                        maskClosable={false}
                        title="提示"
                        footer={[
                            // { text: '取消', onPress: handleCancel },
                            { text: '我知道了', onPress: handleOk }
                        ]}
                    >
                        <strong>修改个人档案即代表您已认真阅读并同意接受以下声明:</strong>
                        <br />
                        1、个人档案中所提供的信息是全面且准确的；
                        <br />
                        2、公司可对个人档案中有关的信息进行调查，公司亦有权查阅本人各种材料以及向第三方做个人访谈（如应聘者原雇主、家庭成员、业务联系人、经济来源人、朋友等）。
                        <br />
                        3、由于本人提供虚假信息的，公司方面有权在核实后随时终止劳动合同。
                    </Modal>
                </div>
            ) : null}
        </>
    );
};

export default withRouter(EntryEmployeeDetailMobile);
